package com.yuwei.base

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType
import java.text.SimpleDateFormat

abstract class BaseActivity<VDB : ViewDataBinding,VM : BaseViewModel> : AppCompatActivity(){
    //拿到集成BaseActivity之后的实际Activity(子类)中的2个泛型
    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }

    protected val binding: VDB by lazy {
        //拿到第一个泛型的class
        val clazz = type[0] as Class<VDB>
        //通过反射,拿到activity中inflate的方法
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)
        //通过反射放大的调用,自定绑定第一个参数的值(布局)
        method.invoke(null, layoutInflater) as VDB
    }

    //直接通过泛型拿到对应的ViewModel的class,来进行实例化
    protected val vm: VM by lazy {
        val clazz = type[1] as Class<VM>
        ViewModelProvider(this)[clazz]
    }

    open fun onError(t: Throwable) {
        Log.e("TagA", "error:${t.message}")
        t.printStackTrace()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        vm.onFailed.observe(this, ::onError)
        //与上面方法是等价的
//        vm.onFailed.observe(this, object : Observer<Throwable> {
//            override fun onChanged(t: Throwable?) {
//                onError(t!!)
//            }
//        })
        initView()
        initData()
    }

    abstract fun initView()
    abstract fun initData()
    fun getTime() : String{
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        return sdf.format(System.currentTimeMillis())
    }
}